<?php

namespace app\api\controller;
use ba\Tree;
use Throwable;
use think\facade\Request;
use think\facade\Db;
use think\facade\Config;
// use app\common\controller\Frontend;
use app\admin\model\Device as DeviceModel;
use app\admin\model\WeighRecord;
use app\admin\model\cans\Parameter;
use app\common\controller\Api;
use app\common\library\token\TokenExpirationException;
use app\api\validate\Device as DeviceValidate;
use app\common\library\Mqtt;
class Device extends Api
{	
	 /**
     * 绑定设备
     * author：mozi
     * time:2025.05.16
     * */
	function add(){
		$params = $this->request->post("");
		$validate = new DeviceValidate();
		$device_id = $params['id'] ?? '';
        try {
            $validate->scene("edit")->check($params);
        } catch (Throwable $e) {
            //$this->error();
            return json(['code'=>100,'msg'=>$e->getMessage()]);
        }
        $model = new DeviceModel();
        $model->startTrans();
        try {
        	if(isset($params['id'])){
        			$find = $model->where(['id'=>$device_id,'agent_id'=>request()->adminId])->find();
		        	if(!$find){
		        		 return json(['code'=>100,'msg'=>'未检测到设备']);
		        	}
		        	// $params['is_bang'] = 1;
		        	// $params['warranty_effect_time'] =time() + $params['warranty_day']*24*60*60;

		            $model->where("id",$find->id)->update([
		            	 'name'=>$params['name'] ?? '',
		            	 'code'=>$params['qr_code'] ??'',
		            	 'imei'=>$params['code'] ?? '',
		            	 'imgs'=>$params['imgs'],
		            	 'remarks'=>$params['remarks'],
		            	 'space_id'=>$params['space'] ?? 0,
		            	 'address'=>$params['device_address'] ?? '',
		            	 'type'=>$params['type'] ?? 0,
		            	 'lat'=>$params['space_latitude'] ?? '',
		            	 'lon'=>$params['space_longitude'] ?? '',

		            ]);
        	}else{
        		  $params['agent_id'] = request()->adminId;
        		  $model->save($params);
        	}
            $model->commit();
        } catch (Throwable $e) {

            $model->rollback();
            $this->error($e->getMessage());
        }
		return json(['code'=>200,'msg'=>'ok']);
	}

	/**
     * 设备校准 测试用  
     * author：mozi
     * time:2025.05.16
     * */
	function complete_calib(){
			$r = Mqtt::send("867896079638535",json_encode(['head'=>'re_calib','biz_no'=>'123','action'=>2,'target'=>380]));  // 给设备发校验指令
			return json(['code'=>200,'msg'=>'ok','data'=>$r]);
	}

	/**
	 * 保存设备配置
	 * */
	function saveSettings(){
		$params = $this->request->post("");
		$device_id = $params['device_id'] ?? 0;
		if($device_id == 0 || $device_id==''){
			  return json(['code'=>100,'msg'=>'设备id不存在']);
		} 
        $model = new DeviceModel();
        $model->startTrans();
        try {
        	unset($params['device_id']);
        	$model->where("id",$device_id)->update(['settings'=>json_encode($params)]);
            $model->commit();
        } catch (Throwable $e) {

            $model->rollback();
            $this->error($e->getMessage());
        }
		return json(['code'=>200,'msg'=>'ok']);
	}
	 /**
     * 获取设备列表
     * author：mozi
     * time:2025.05.16
     * */
	function lists(){
		if (Request::isPost()) {
	       
	        $page = $this->request->post("pageNum",1);
	        $pageSize =  $this->request->post("pageSize",10);
	        $status = $this->request->post("status",0);
	        $key = $this->request->post("keyword",'');
	        $space_id = $this->request->post("placeId",0);
	        $type = $this->request->post("deviceType",0);
	        $w= [];
	        // $w['status'] = $status;
	        if($key){
                $w[] = ['name|code',"like","%".$key."%"];
	        }
	        if($space_id){
	        	 $w[] = ['space_id','=',$space_id];
	        }
	        if($type){
	        	 $w[] = ['type','=',$type];
	        }
		    $model = new DeviceModel();
		    $res = $model
		    ->where("agent_id", request()->adminId)
		    ->where($w)
		    ->order("id desc")
		    ->field("code,name,status,imei")  // 只查询 device 表的 code 和 name 字段 和 merchant表里字段，field里一定要有关联外键 merchant_id ，否则查询不出来
		    ->page($page, $pageSize)
		    ->select();

		   $total =   $model->where("agent_id", request()->adminId)->where($w)->count();
		   return json(['code'=>200,'msg'=>'ok','data'=>$res??[],'total'=>$total ?? 0]);
	 
        }
		
	}

	 /**
	 * 获取最近的称重记录 用于投诉的时候选择
     * author：mozi
     * time:2025.05.16
	 * */
	function weighLatest()
	{
		if (Request::isPost()) {
	        $code = $this->request->post("code",'');
			if($code){
				    $model = new DeviceModel();
				    $res = $model->where('code',$code)->find();
				    if(!$res){
				    	$this->error("数据异常");
				    }

				    $data = WeighRecord::where("device_id",$res->id)->limit(3)->order("id desc")->select();
				   
				   return json(['code'=>200,'msg'=>'ok','data'=>$data??[]]);
			}else{
				  return json(['code'=>100,'msg'=>'市场id缺失,无法获取','data'=>$r??[]]);
			}
        }
	}

	/**
	 * 获取参数类型
     * author：mozi
     * time:2025.05.16
	 * */
	function cans(){
		 if (Request::isPost()) {
	        $tid = $this->request->post("type_id",0);
			if($tid){
				   $res = Parameter::where('type_id',$tid)->select();
				   return json(['code'=>200,'msg'=>'ok','data'=>$res??[]]);
			}else{
				  return json(['code'=>100,'msg'=>'市场id缺失,无法获取']);
			}
        }
	}

	/**
	 * 设备调试
     * author：mozi
     * time:2025.05.16
	 * */
	function deviveDebug(){
		 if (Request::isPost()) {
	        $code = $this->request->post("code",'');
	        $weight = $this->request->post("weight",''); //砝码
	        $act = $this->request->post("act",''); //动作类型
			if($code){
				   if($weight == ''){
				   	  $this->error("请输入砝码重量");
				   }
				   $res = DeviceModel::where('code',$code)->whereOr("imei",$code)->find();
				   if(!$res){
				   	   return json(['code'=>100,'msg'=>'设备不存在']);
				   }
				   if($res){
				   	 	switch ($act) {
				   	 		case 'start':
				   	 			$r = Mqtt::send($res->imei,json_encode(['head'=>'re_calib','biz_no'=>'123','action'=>1,'target'=>intval($weight)]));  // 给设备 开始标定 指令
				   	 			return json(['code'=>200,'msg'=>'ok']);
				   	 			break;
				   	 		case 'complete':
				   	 			$r = Mqtt::send($res->imei,json_encode(['head'=>'re_calib','biz_no'=>'xxx','action'=>2,'target'=>intval($weight)]));  // 给设备 完成标定 指令
				   	 			return json(['code'=>200,'msg'=>'ok']);
				   	 			break;
				   	 		default:
				   	 			// code...
				   	 			break;
				   	 	}
				   }
				   
			}else{
				  return json(['code'=>100,'msg'=>'市场id缺失,无法获取','data'=>$r??[]]);
			}
        }
	}


	/**
	 * 设备详细
     * author：mozi
     * time:2025.05.16
	 * */
	function details(){
		 if (Request::isPost()) {
	        $imei = $this->request->post("imei",'');
			if($imei){
				   $res = DeviceModel::where('imei',$imei)->where("agent_id",request()->adminId)->find();
				   if(!empty($res['settings'])){
				   	   $res['settings'] = json_decode($res['settings'],true);
				   }
				   return json(['code'=>200,'msg'=>'ok','data'=>$res??[]]);
				   
			}else{
				  return json(['code'=>100,'msg'=>'市场id缺失,无法获取']);
			}
        }
	}

	/**
	 * 开启停用设备
     * author：mozi
     * time:2025.05.16
	 * */
	function deviceStatus(){
		if (Request::isPost()) {
	        $status = $this->request->post("status",'');
	        $imei = $this->request->post("imei",'');
			if(!empty($status)){
				   $res = DeviceModel::where('imei',$imei)->where("agent_id",request()->adminId)->update(['status'=>($status == 'start') ? 1 : 0]);
				   if($res){
				   	 return json(['code'=>200,'msg'=>'ok']);
				   }else{
				   	  $this->error("操作失败");
				   }
			}else{
				  return json(['code'=>100,'msg'=>'错误操作']);
			}
        }  
	}
	/**
	 * 删除设备
     * author：mozi
     * time:2025.05.16
	 * */
	function deviceDel(){
		if (Request::isPost()) {
	        $imei = $this->request->post("imei",'');
			if($imei){
				   $res = DeviceModel::where('imei',$imei)->where("agent_id",request()->adminId)->delete();
				   if($res){
				   	 return json(['code'=>200,'msg'=>'ok']);
				   }else{
				   	  $this->error("操作失败");
				   }
			}else{
				  return json(['code'=>100,'msg'=>'参数缺失，无法删除']);
			}
        }  
	}
	/**
	 * 扫码开启设备
     * author：mozi
     * time:2025.05.16
	 * */
	function start(){
		 if (Request::isPost()) {
	        $imei = $this->request->post("imei",'');
			if($imei){
				   $res = DeviceModel::where('imei',$imei)->whereOr("code",$imei)->find();
				   if($res['settings']){
				   	   $res['settings'] = json_decode($res['settings'],true);
				   }
				   return json(['code'=>200,'msg'=>'ok','data'=>$res??[]]);
				   
			}else{
				  return json(['code'=>100,'msg'=>'市场id缺失,无法获取']);
			}
        }
	}
}